/***********************************************************************************************************************
* Copyright (c) 2020, China Mobile Communications Group Co.,Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with 
* the License. You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @file        opencc_mng.c
*
* @brief       Inner control part of character conversion.
*
* @revision
* Date         Author          Notes
* 2020-11-20   OneOS Team      First Version
***********************************************************************************************************************
*/
#include <stdlib.h>
#include "opencc_mng.h"

static int cc_is_inited = 0;
static cc_charc_set_t *cc_mng_charc_set_entry[CC_CHARC_TYPE_END] = {NULL};

int cc_get_char_byte_and_count(opencc_info_t *src, cc_charc_set_t *src_entry, 
                                                int *char_count, int *byte_count)
{
    
    unsigned long code_point = 0;
    int chars = 0;
    int bytes = 0;
    int size = 0;
    int ret = 0;
    const char *pSrc = src->buf;
    
    if (src->buf_size < 0)
    {
        src->buf_size = CC_INT_MAX;
    }
    
    size = src->buf_size;
    while (size > 0)
    {
        ret = src_entry->charc_set_to_unicode(pSrc, size, &code_point);
        if (code_point == 0)
        {
            break;
        }
        size -= ret;
        pSrc += ret;
        bytes += ret;
        chars++;
    }

    *char_count = chars;
    *byte_count = bytes;
    return 0;
}


cc_charc_set_t *cc_mng_get_entry_by_type(CC_COMMON_CHARACTER_TYPE_E type)
{
    int i = 0;

    for (i = 0; i < CC_CHARC_TYPE_END; i++)
    {
        if (cc_mng_charc_set_entry[i] == NULL)
        {
            continue;
        }
    
        if (type == cc_mng_charc_set_entry[i]->charc_type)
        {
            return cc_mng_charc_set_entry[i];
        }
    }

    return NULL;
}

int cc_init(void)
{
    if (cc_is_inited == 0) 
    {
        cc_mng_charc_set_entry[CC_CHARC_TYPE_UTF8] = cc_utf8_get_entry();
        cc_mng_charc_set_entry[CC_CHARC_TYPE_GBK] = cc_gbk_get_entry();
        cc_mng_charc_set_entry[CC_CHARC_TYPE_UTF16_LE] = cc_utf16LE_get_entry();
        cc_mng_charc_set_entry[CC_CHARC_TYPE_UTF16_BE] = cc_utf16BE_get_entry();
        cc_mng_charc_set_entry[CC_CHARC_TYPE_ISO9959] = cc_iso8859_get_entry();
        cc_mng_charc_set_entry[CC_CHARC_TYPE_GSM7] = cc_GSM7_get_entry();
        cc_is_inited = 1;
    }
 
    return 0;
}


